package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Service.SetmealService;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)//绑定确认方法实现
@Transactional//事务管理
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetmealDao setmealDao;

    //添加

    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        setSetmealAndCheckgroup(setmealId,checkgroupIds);
        savePic2DbRedis(setmeal.getImg());

    }

    //分页查询

    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.findByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal> list = page.getResult();

        generateMobileStaticHtml();//静态页面生成

        return new PageResult(total,list);


    }


    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }


    public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
        return setmealDao.findCheckGroupIdsBySetmealId(setmealId);
    }


    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        String pre_img = setmealDao.findById(setmeal.getId()).getImg();
        deletePicFromDbRedis(pre_img);
        setmealDao.edit(setmeal);
        setmealDao.deleteAssociationBySetmealId(setmeal.getId());
        setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
        savePic2DbRedis(setmeal.getImg());

    }


    public void delete(Integer id) {
       Setmeal setmeal= setmealDao.findById(id);
        setmealDao.deleteAssociationBySetmealId(id);
        setmealDao.deleteSetmeal(id);
        deletePicFromDbRedis(setmeal.getImg());
    }


    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAll();
    }

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private CheckItemDao checkItemDao;

    //详情查询一
    public Setmeal findEverythingById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        List<CheckGroup> CGlist = new ArrayList<>();
        List<Integer> checkGroupIds = setmealDao.findCheckGroupIdsBySetmealId(id);
        for (int m = 0;m < checkGroupIds.size(); m++) {
            CheckGroup checkGroup = checkGroupDao.findById(checkGroupIds.get(m));
            List<CheckItem> CIlist = new ArrayList<>();
            Integer[] checkItemIds = checkGroupDao.findCheckItemIdsByCheckGroupId(checkGroup.getId());
            for (int j = 0; j < checkItemIds.length; j++) {
                CheckItem checkItem = checkItemDao.findById(checkItemIds[j]);
               CIlist.add(checkItem);
            }
            CGlist.add(checkGroup);
        }
        setmeal.setCheckGroups(CGlist);
        return setmeal;
    }



    //详情查询二
    public Setmeal findDetailById(Integer id){
        Setmeal setmeal = setmealDao.findById(id);
        List<CheckGroup> groupList = checkGroupDao.findAllBySetmealId(id);
        if(groupList != null && groupList.size() > 0){
            for (CheckGroup checkGroup : groupList) {
                List<CheckItem> itemList = checkItemDao.findAllByCheckGroupId(checkGroup.getId());
                checkGroup.setCheckItems(itemList);
            }
        }
        setmeal.setCheckGroups(groupList);
        return setmeal;
    }
    //详情查询三
    public Setmeal getAllSetmealDetail(Integer id) {
        return setmealDao.findById4Detail(id);
    }





    //添加关系表
    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length >0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmeal_id",setmealId);
                map.put("checkgroup_id",checkgroupId);
                setmealDao.setAssociation(map);
            }
        }
    }

    //Redis图片存删
    private void savePic2DbRedis(String img){
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisConstant.SETMEAL_PIC_DBRESOURCE,img);
        resource.close();
    }

    private void deletePicFromDbRedis(String img){
        Jedis resource = jedisPool.getResource();
        resource.srem(RedisConstant.SETMEAL_PIC_DBRESOURCE,img);
        resource.close();
    }



    @Autowired
     private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.getAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById4Detail(setmeal.getId()));
            generteHtml("m_setmeal_detail.ftl","m_setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取套餐预约占比数据
    public List<Map<String, Object>> getSetmealReport() {
       return setmealDao.getSetmealReport();


    }







}
